﻿using Furion;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Pear.Application.UserCenter.Common;
using Pear.Core;
using Pear.Core.Entities.LiveCenter;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pear.Application.LiveCenter.LiveServices
{

    /// <summary>
    /// 设备服务
    /// </summary>
    [ApiDescriptionSettings(ApiGroupConsts.LiveCenter)]
    [AllowAnonymous]
    public class VideoAppService : IDynamicApiController, ITransient
    {

        //1.构造函数注入
        SqlSugar.ISqlSugarClient _db;
        public VideoAppService(ISqlSugarClient db)
        {

            this._db = db;
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [SecurityDefine(SecurityConsts.USER_SERVICE_LIST), HttpGet, ApiDescriptionSettings(Name = "list")]
        public async Task<PagedList<VideoModel>> GetListAsync([FromQuery, Required] BaseListInput input)
        {
            var hasKeyword = !string.IsNullOrEmpty(input.Keyword?.Trim());


            var devices = _db.Queryable<VideoModel>().ToPagedList(input.PageIndex, input.PageSize);

            return devices.Adapt<PagedList<VideoModel>>();
        }


        /// <summary>
        /// 获取列表
        /// </summary> 
        /// <returns></returns>
        [SecurityDefine(SecurityConsts.USER_SERVICE_LIST), HttpGet, ApiDescriptionSettings(Name = "GetLiveUrl")]
        public async Task<string> GetUrlByDeviceAsync([FromQuery, Required] string deviceCode)
        {


            var device = _db.Queryable<DeviceModel>().Where(q => q.Code == deviceCode).First();

            if (device == null)
            {
                throw new Exception($"无效的设备:{deviceCode}");
            }

            //如果设置有指定播放地址直接返回
            if(!string.IsNullOrWhiteSpace(device.VideoUrl))
            {
                return device.VideoUrl;
            }

            var video = _db.Queryable<VideoModel>().Where(q => q.Enabled).First();

            if (video == null || string.IsNullOrWhiteSpace(video.Url))
            {
                return "";
            }
            var url= video.Url.Trim();
            if (url.Contains("http"))
            {
                return url;
            }
            else
            {
                url = $"http://{App.HttpContext.Request.Host.ToString()}/{url}";
            }
            return url;
        }

        /// <summary>
        /// 获取当前视频信息
        /// </summary>
        /// <returns></returns>
        [SecurityDefine(SecurityConsts.USER_SERVICE_PROFILE_SELF), HttpGet]
        public VideoModel Profile(int id)
        {
            var model = _db.Queryable<VideoModel>().InSingle(id);
            return model;
        }


        /// <summary>
        /// 新增 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [SecurityDefine(SecurityConsts.USER_SERVICE_ADD), ApiDescriptionSettings(KeepVerb = true)]
        public async Task<VideoModel> AddAsync([Required] AddVideoInput input)
        {
            var model = input.Adapt<VideoModel>();
            model.CreateTime = DateTime.Now;
            model.Id = await _db.Insertable<VideoModel>(model).ExecuteReturnBigIdentityAsync();
            if (model.Id > 0)
            {
                model = _db.Queryable<VideoModel>().InSingle(model.Id);
                return model;
            }
            throw new NotImplementedException("添加失败");
        }



        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="videoIds"></param>
        /// <returns></returns>
        [SecurityDefine(SecurityConsts.USER_SERVICE_DELETE), HttpDelete]
        public async Task DeleteAsync([Required, MinLength(1), MaxLength(20), FromBody] int[] videoIds)
        {
            // 判断用户Id中是否有重复项
            var isRepeat = videoIds.GroupBy(i => i).Any(g => g.Count() > 1);
            if (isRepeat) throw Oops.Oh(SystemErrorCodes.u1011);


            if (_db.Deleteable<VideoModel>(videoIds).ExecuteCommand() <= 0)
            {
                throw Oops.Oh("删除失败");
            }
        }


        /// <summary>
        /// 编辑信息
        /// </summary> 
        /// <param name="input"></param>
        /// <returns></returns>
        [SecurityDefine(SecurityConsts.USER_SERVICE_MODIFY), HttpPut]
        public async Task<VideoModel> ModifyAsync([Required] ModifyVideoInput input)
        {
            if (input.Id <= 0)
            {
                throw new NotImplementedException("无效的视频信息");
            }
            var model = input.Adapt<VideoModel>();
            model.UpdateTime = DateTime.Now;
            var row = await _db.Updateable<VideoModel>(model).IgnoreColumns(q => q.CreateTime).ExecuteCommandAsync();
            if (row > 0)
            {
                model = _db.Queryable<VideoModel>().InSingle(model.Id);
                return model;
            }
            throw new NotImplementedException("修改失败");
        }

    }
}
